package com.yuzhi.master.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.yuzhi.common.annotation.Log;
import com.yuzhi.common.contant.UserConstants;
import com.yuzhi.common.core.controller.BaseController;
import com.yuzhi.common.core.domain.ApiResult;
import com.yuzhi.common.core.domain.BaseEntity;
import com.yuzhi.common.core.domain.entity.SysDept;
import com.yuzhi.common.core.domain.entity.SysRole;
import com.yuzhi.common.core.domain.entity.SysUser;
import com.yuzhi.common.core.domain.model.PassWordBody;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.enums.BusinessTypeEnum;
import com.yuzhi.common.enums.LoginTypeEnum;
import com.yuzhi.common.excel.ExcelResult;
import com.yuzhi.common.helper.LoginHelper;
import com.yuzhi.common.util.StreamUtils;
import com.yuzhi.common.util.StringUtils;
import com.yuzhi.common.util.poi.ExcelUtil;
import com.yuzhi.framework.config.properties.AesKeyPropertiesConfig;
import com.yuzhi.system.domain.request.SysDeptReq;
import com.yuzhi.system.domain.request.SysRoleReq;
import com.yuzhi.system.domain.request.SysUserReq;
import com.yuzhi.system.domain.vo.SysUserExportVo;
import com.yuzhi.system.domain.vo.SysUserImportVo;
import com.yuzhi.system.listener.SysUserImportListener;
import com.yuzhi.system.service.ISysDeptService;
import com.yuzhi.system.service.ISysRoleService;
import com.yuzhi.system.service.ISysUserService;
import com.yuzhi.system.service.SysLoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author auto
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
@Tag(name = "用户管理")
public class SysUserController extends BaseController {

    private final SysLoginService sysLoginService;
    private final ISysUserService userService;
    private final ISysRoleService roleService;
    private final ISysDeptService deptService;
    @Autowired
    private AesKeyPropertiesConfig aesKeyPropertiesConfig;
    /**
     * 获取用户列表
     */
    @Operation(
            summary = "获取用户列表",
            description = "获取用户列表"
    )
    @SaCheckPermission("system:user:list")
    @PostMapping("/list")
    public ApiResult<PageDataInfo<SysUser>> list(@RequestBody SysUserReq user) {
        return ApiResult.ok(userService.selectPageUserList(user));
    }

    /**
     * 导出用户列表
     */
    @Log(title = "用户管理", businessType = BusinessTypeEnum.EXPORT)
    @SaCheckPermission("system:user:export")
    @PostMapping("/export")
    public void export(@RequestBody SysUserReq user, HttpServletResponse response) {
        List<SysUser> list = userService.selectUserList(user);
        List<SysUserExportVo> listVo = BeanUtil.copyToList(list, SysUserExportVo.class);
        for (int i = 0; i < list.size(); i++) {
            List<SysDept> depts = list.get(i).getDepts();
            SysUserExportVo vo = listVo.get(i);
            if (CollUtil.isNotEmpty(depts)) {
                String deptName = Convert.toStr(depts.stream().map(SysDept::getDeptName).collect(Collectors.toList()));
                String leader = Convert.toStr(depts.stream().map(SysDept::getLeader).collect(Collectors.toList()));
                vo.setDeptName(deptName);
                vo.setLeader(leader);
            }
        }
        ExcelUtil.exportExcel(listVo, "用户数据", SysUserExportVo.class, response);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "用户管理", businessType = BusinessTypeEnum.IMPORT)
    @SaCheckPermission("system:user:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<SysUserImportVo> result = ExcelUtil.importExcel(file.getInputStream(), SysUserImportVo.class, new SysUserImportListener(updateSupport));
        return ApiResult.ok(result.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "用户数据", SysUserImportVo.class, response);
    }

    /**
     * 根据用户编号获取详细信息
     *
     * @param userId 用户ID
     */
    @SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public ApiResult<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) String userId) {
        userService.checkUserDataScope(userId);
        Map<String, Object> ajax = new HashMap<>();
        if (ObjectUtil.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            if (CollUtil.isNotEmpty(sysUser.getDepts())){
                sysUser.setDeptIds(sysUser.getDepts().stream().map(SysDept::getId).toArray(String[]::new));
            }
          if (CollUtil.isNotEmpty(sysUser.getRoles())){
              sysUser.setRoleIds(sysUser.getRoles().stream().map(SysRole::getId).toArray(String[]::new));
          }

            ajax.put("user", sysUser);
        }
        return ApiResult.ok(ajax);
    }

    /**
     * 新增用户
     */
    @SaCheckPermission("system:user:add")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.INSERT)
    @PostMapping
    public ApiResult<Void> add(@Validated @RequestBody SysUser user) {
        String[] deptIds = user.getDeptIds();
        for (int j = 0; j < deptIds.length; j++) {
            deptService.checkDeptDataScope(deptIds[j]);
        }

        if (!userService.checkUserNameUnique(user)) {
            return ApiResult.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return ApiResult.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return ApiResult.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public ApiResult<Void> edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        String[] deptIds = user.getDeptIds();
        for (int j = 0; j < deptIds.length; j++) {
            deptService.checkDeptDataScope(deptIds[j]);
        }
        if (!userService.checkUserNameUnique(user)) {
            return ApiResult.fail("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return ApiResult.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return ApiResult.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     *
     * @param userIds 角色ID串
     */
    @SaCheckPermission("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{userIds}")
    public ApiResult<Void> remove(@PathVariable String[] userIds) {
        if (ArrayUtil.contains(userIds, getUserId())) {
            return ApiResult.fail("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @SaCheckPermission("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/resetPwd")
    public ApiResult<Void> resetPwd(@RequestBody PassWordBody passWordBody) {
        SysUser sysUser = userService.selectUserById(passWordBody.getUserId());
        userService.checkUserAllowed(sysUser);
        userService.checkUserDataScope(sysUser.getId());
        //解密
        String password = SecureUtil.aes(aesKeyPropertiesConfig.getKey().getBytes()).decryptStr(passWordBody.getPassword());
        sysUser.setPassword(BCrypt.hashpw(password));
        return toAjax(userService.resetPwd(sysUser));
    }


    /**
     * 修改密码
     */
    //@SaCheckPermission("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/updatePwd")
    public ApiResult<Void> updatePwd(@RequestBody PassWordBody passWordBody) {
        SysUser sysUser = userService.selectUserById(passWordBody.getUserId());
        String oldPassword = SecureUtil.aes(aesKeyPropertiesConfig.getKey().getBytes()).decryptStr(passWordBody.getOldPassword());
        //校验老密码是否正确
        if (!BCrypt.checkpw(oldPassword, sysUser.getPassword())){
            return ApiResult.fail("修改密码失败，旧密码错误");
        }

        String password = SecureUtil.aes(aesKeyPropertiesConfig.getKey().getBytes()).decryptStr(passWordBody.getPassword());

        sysUser.setPassword(BCrypt.hashpw(password));
        return toAjax(userService.resetPwd(sysUser));
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping("/changeStatus")
    public ApiResult<Void> changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     *
     * @param userId 用户ID
     */
    @SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public ApiResult<Map<String, Object>> authRole(@PathVariable String userId) {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", LoginHelper.isAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isAdmin()));
        return ApiResult.ok(ajax);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户Id
     * @param roleIds 角色ID串
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessTypeEnum.GRANT)
    @PutMapping("/authRole")
    public ApiResult<Void> insertAuthRole(String userId, String[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return ApiResult.ok();
    }

    /**
     * 获取部门树列表
     */
    @SaCheckPermission("system:dept:list")
    @PostMapping("/deptTree")
    public ApiResult<List<Tree<String>>> deptTree(@RequestBody SysDeptReq dept) {
        return ApiResult.ok(deptService.selectDeptTreeList(dept));
    }

    /**
     * 组装 用户能看到的部门数据
     */
    @SaCheckPermission("system:user:edit")
    @PostMapping("/refreshAllUserDataScope")
    public ApiResult refreshUserDataScope() {
        if (LoginHelper.isAdmin()){
            //只有管理员可以操作此接口
            List<String> userIds = userService.selectUserList(new SysUserReq()).stream().map(BaseEntity::getId).distinct().collect(Collectors.toList());
            userService.refreshUserDataScope(userIds);
        }
        return ApiResult.ok();
    }

}
